package com.ruoyi.system.wx.login;

import org.apache.commons.codec.digest.DigestUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName WxPaySignUtil
 * @Description
 * @Author sizegang
 * @Date2025/4/22 22:19
 **/
public class WxPaySignUtil {
    public static String generateSignature(Map<String, String> params, String key) {
        // 1. 参数按ASCII码排序
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        // 2. 拼接成key=value&格式
        StringBuilder sb = new StringBuilder();
        for (String k : keys) {
            if (params.get(k) != null && !"".equals(params.get(k)) && !"sign".equals(k)) {
                sb.append(k).append("=").append(params.get(k)).append("&");
            }
        }
        sb.append("key=").append(key);

        // 3. MD5加密并转大写
        return DigestUtils.md5Hex(sb.toString()).toUpperCase();
    }

    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }
}
